package com.kfm.jdbc.day0405;

import java.time.LocalDateTime;

public class Cook {

    private String bread;

    public synchronized void eat(){
        System.out.println(Thread.currentThread().getName() + " eat()");
        if (bread == null){
            try {
                // 没有面包，等待
//                Thread.sleep(10000);
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } else {
            System.out.println(Thread.currentThread().getName() + " Eat bread: " + bread);
            bread = null;
            notifyAll();
        }
    }

    public synchronized void cook(){
        System.out.println("cook");
        if (bread != null){
            try {
                // 已经有面包了，等待
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        bread = LocalDateTime.now().toString();
        notify();
        System.out.println("Cooked bread: " + bread);
    }
}


class CookThread extends Thread{

    private Cook cook;

    public CookThread(Cook cook) {
        this.cook = cook;
    }

    @Override
    public void run() {
        while (true){
            cook.cook();
        }
    }
}

class EatThread extends Thread{

    private Cook cook;

    public EatThread(Cook cook, String name) {
        super(name);
        this.cook = cook;
    }

    @Override
    public void run() {
        while (true){
            cook.eat();
        }
    }
}
